package vip.xiaonuo.smzq.modular.dictionary.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.smzq.core.utils.ParamUtil;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb08Xzqh;
import vip.xiaonuo.smzq.modular.dictionary.entity.vo.DirTree;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb08XzqhMapper;
import vip.xiaonuo.smzq.modular.dictionary.service.ICb08XzqhService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.smzq.modular.user.entity.Org;
import vip.xiaonuo.smzq.modular.user.entity.Position;
import vip.xiaonuo.smzq.modular.user.entity.User;
import vip.xiaonuo.smzq.modular.user.mapper.OrgMapper;
import vip.xiaonuo.smzq.modular.user.mapper.PositionMapper;
import vip.xiaonuo.smzq.modular.user.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 行政区划 服务实现类
 *
 * @author eomer
 * @since 2024-02-21
 */
@Service
public class Cb08XzqhServiceImpl extends ServiceImpl<Cb08XzqhMapper, Cb08Xzqh> implements ICb08XzqhService {

    @Resource
    private Cb08XzqhMapper cb08XzqhMapper;

    @Resource
    private OrgMapper orgMapper;//级别部省市县填报
    @Resource
    private PositionMapper positionMapper;//所对应的行政区划
    @Resource
    private UserMapper userMapper;//用户

    @Resource
    private CommonCacheOperator commonCacheOperator;//缓冲机制

    @Override
    public Page<Cb08Xzqh> page(Cb08Xzqh cb08Xzqh) {
        QueryWrapper<Cb08Xzqh> queryWrapper = new QueryWrapper<>();
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    /**
     * 行政区划目录树
     *
     * @param fdm 父节点代码
     */
    @Override
    public DirTree getXzqhDirTree(Integer fdm) {


        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();

        if (saBaseLoginUser!=null){
            User user = userMapper.selectById(saBaseLoginUser.getId());
            //Org org = orgMapper.selectById(user.getOrgId());

            if (user.getOrgId()!=null&&user.getOrgId().length()>0){
                if (user.getOrgId().equals("-1")){
                    fdm=130000;
                }else{
                    fdm=Integer.valueOf(user.getOrgId());
                }
            } else if (fdm==null){
                fdm=130000;
            }
            if (fdm==0){
                // 从缓存中取
                Object cacheValue = commonCacheOperator.get(ParamUtil.STORAGE_XZQH_TREEKEY);
                if(ObjectUtil.isNotEmpty(cacheValue)) {
                    return JSONUtil.toBean(String.valueOf(cacheValue) , DirTree.class);
                }
            }

        }else{
            if (fdm==0){
                // 从缓存中取
                Object cacheValue = commonCacheOperator.get(ParamUtil.STORAGE_XZQH_TREEKEY);
                if(ObjectUtil.isNotEmpty(cacheValue)) {
                    return JSONUtil.toBean(String.valueOf(cacheValue), DirTree.class);
                }
            }
        }
        DirTree dirTree = new DirTree();
        try {
            if (0 != fdm) {
                QueryWrapper<Cb08Xzqh> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("dm", fdm);
                Cb08Xzqh cb08Xzqh = cb08XzqhMapper.selectOne(queryWrapper);
                dirTree.setId(cb08Xzqh.getPkid());
                dirTree.setName(cb08Xzqh.getMc()+"("+cb08Xzqh.getDm()+")");
                dirTree.setXzqhmc(cb08Xzqh.getMc());
                dirTree.setPId(String.valueOf(cb08Xzqh.getFdm()));
                dirTree.setCode(String.valueOf(cb08Xzqh.getDm()));
                 List<DirTree>  dirTrees=getXzqhDirTreeList(cb08Xzqh.getDm());
                if (dirTrees!=null&&dirTrees.size()>0){
                    dirTree.setChildren(dirTrees);
                }
            }else{
                dirTree.setId("0");
                dirTree.setName("全国");
                dirTree.setXzqhmc("全国");
                dirTree.setPId("0");
                dirTree.setCode("0");
                List<DirTree>  dirTrees=getXzqhDirTreeList(0);
                if (dirTrees!=null&&dirTrees.size()>0){
                    dirTree.setChildren(dirTrees);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
           if (fdm==0){
               commonCacheOperator.put(ParamUtil.STORAGE_XZQH_TREEKEY, JSONUtil.toJsonStr(dirTree));
           }

        return dirTree;
    }

    public List<DirTree> getXzqhDirTreeList(Integer fdm){
        List<DirTree> dirTreeList = new ArrayList<>();
        try{
            QueryWrapper<Cb08Xzqh> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("fdm", fdm);
            List<Cb08Xzqh> cb08XzqhList = cb08XzqhMapper.selectList(queryWrapper);
            for (Cb08Xzqh cb08Xzqh : cb08XzqhList) {
                List<DirTree> dirTrees = new ArrayList<>();
                DirTree dirTree = new DirTree();
                dirTree.setId(cb08Xzqh.getPkid());
                dirTree.setName(cb08Xzqh.getMc()+"("+cb08Xzqh.getDm()+")");
                dirTree.setXzqhmc(cb08Xzqh.getMc());
                dirTree.setPId(String.valueOf(cb08Xzqh.getFdm()));
                dirTree.setCode(String.valueOf(cb08Xzqh.getDm()));
                dirTrees=getXzqhDirTreeList(cb08Xzqh.getDm());
                if (dirTrees!=null&&dirTrees.size()>0){
                    dirTree.setChildren(dirTrees);
                }else{
                    dirTree.setChildren(new ArrayList<DirTree>());
                }
                dirTreeList.add(dirTree);
            }
        }catch (Exception e){
            System.out.println(e);
        }

        return dirTreeList;
    }

    /**
     * 查询行政区划目录树-重构
     *
     * @param fdm
     * @author Kevin
     * @since 2024/7/22 14:58
     */
    @Override
    public DirTree getXzqhTree(Integer fdm) {
        DirTree dirTree = new DirTree();

        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        if (saBaseLoginUser != null){
            User user = userMapper.selectById(saBaseLoginUser.getId());
            if (user.getOrgId()!=null&&user.getOrgId().length()>0){
                if (user.getOrgId().equals("-1")){
                    fdm=130000;
                }else{
                    fdm=Integer.valueOf(user.getOrgId());
                }
            } else if (fdm==null){
                fdm=130000;
            }
        }

        //从缓存中获取
        //全国
        if (fdm == 0){
            Object cacheValue = commonCacheOperator.get("xzqhTreeChina");
            if(ObjectUtil.isNotEmpty(cacheValue)) {
                return JSONUtil.toBean(String.valueOf(cacheValue), DirTree.class);
            }
        }
        //河北省
        else if (fdm == 130000){
            Object cacheValue = commonCacheOperator.get("xzqhTreeHebei");
            if(ObjectUtil.isNotEmpty(cacheValue)) {
                return JSONUtil.toBean(String.valueOf(cacheValue), DirTree.class);
            }
        }

        //查询数据库
        List<DirTree> list = getXzqhTreeList(fdm);
        if (CollectionUtil.isNotEmpty(list)) {
            dirTree = list.get(0);
        }
        //全国
        if (fdm == 0){
            commonCacheOperator.put("xzqhTreeChina", JSONUtil.toJsonStr(dirTree));
        } else if (fdm == 130000){
            commonCacheOperator.put("xzqhTreeHebei", JSONUtil.toJsonStr(dirTree));
        }
        return dirTree;
    }

    /**
     * 查询行政区划树列表
     *
     * @param fdm
     * @author Kevin
     * @since 2024/7/22 14:58
     */
    public List<DirTree> getXzqhTreeList(Integer fdm) {

        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();

        if (saBaseLoginUser != null){
            User user = userMapper.selectById(saBaseLoginUser.getId());
            if (user.getOrgId() != null && user.getOrgId().length() > 0){
                if ("-1".equals(user.getOrgId())){
                    fdm = 130000;
                }else{
                    fdm = Integer.valueOf(user.getOrgId());
                }
            } else if (fdm == null){
                fdm = 130000;
            }
        }

        QueryWrapper<Cb08Xzqh> queryWrapper = new QueryWrapper<>();
        //全国的数据查询全部，否则模糊查询
        if (fdm != 0) {
            String dmStr = String.valueOf(fdm).replaceAll("0*$", "");
            queryWrapper.likeRight("CAST(dm AS TEXT)", dmStr);
        }
        List<Cb08Xzqh> list = cb08XzqhMapper.selectList(queryWrapper);

        List<DirTree> result = new ArrayList<>();

        //获取根节点
        //全国
        if (fdm == 0) {
            DirTree node = new DirTree();
            node.setId("0");
            node.setName("全国");
            node.setXzqhmc("全国");
            node.setCode("0");
            node.setPId("0");
            node.setChildren(getChildrenList(node, list));
            result.add(node);
        } else {
            for (Cb08Xzqh item : list) {
                if (fdm.equals(item.getDm())) {
                    DirTree node = new DirTree();
                    node.setId(item.getPkid());
                    node.setName(item.getMc() + "(" + item.getDm() + ")");
                    node.setXzqhmc(item.getMc());
                    node.setCode(String.valueOf(item.getDm()));
                    node.setPId(String.valueOf(item.getFdm()));
                    node.setChildren(getChildrenList(node, list));
                    result.add(node);
                }
            }
        }

        return result;
    }

    /**
     * 递归获取子级
     *
     * @param root
     * @param list
     * @author Kevin
     * @since 2024/7/22 15:00
     */
    private List<DirTree> getChildrenList(DirTree root, List<Cb08Xzqh> list) {
        List<DirTree> children = new ArrayList<>();
        for (Cb08Xzqh item : list) {
            if (String.valueOf(item.getFdm()).equals(root.getCode())) {
                DirTree node = new DirTree();
                node.setId(item.getPkid());
                node.setName(item.getMc()+"("+item.getDm()+")");
                node.setXzqhmc(item.getMc());
                node.setCode(String.valueOf(item.getDm()));
                node.setPId(String.valueOf(item.getFdm()));
                node.setChildren(getChildrenList(node, list));
                children.add(node);
            }
        }
        return children;
    }
}
